package com.sky.task;


import com.sky.constant.OrdersConstant;
import com.sky.dto.OrdersDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * @Auth: cdz
 * @Desc: 处理订单超时未支付/订单完成
 * @Date: 2023/3/16 11:09
 */
@Component
@Slf4j
public class OrderTask {

    @Autowired
    private OrderMapper orderMapper;


    /**
     * 功能描述: 订单超时未支付
     *
     * @return : void
     */

    @Scheduled(cron = "0 * * * * ?")
    public void cancelOrders() {
        //查询订单,根据订单状态,和下单时间
        OrdersDTO dto = new OrdersDTO();
        dto.setStatus(Orders.PENDING_PAYMENT);
        dto.setOrderTime(LocalDateTime.now().minusMinutes(OrdersConstant.ORDER_EXPIRE_TIME));
        List<String> expireOrder = orderMapper.selExpireOrder(dto);
        //关闭微信下单接口
        //修改订单状态
        if (expireOrder == null || expireOrder.size() == 0) {
            return;
        }
        HashMap<String, Object> map = new HashMap<>();
        map.put("expireOrder", expireOrder);
        map.put("status", Orders.CANCELLED);
        map.put("cancelReason", "订单超时未支付");
        map.put("cancelTime", LocalDateTime.now());
        orderMapper.cancel(map);
    }
    /**
     * 处理“派送中”状态的订单
     */
    @Scheduled(cron = "0 0 1 * * ?")
    public void processDeliveryOrder(){
        log.info("处理派送中订单：{}", new Date());
        // select * from orders where status = 4 and order_time < 当前时间-1小时
        LocalDateTime time = LocalDateTime.now().plusMinutes(-60);
        List<Orders> ordersList = orderMapper.getByStatusAndOrdertimeLT(Orders.DELIVERY_IN_PROGRESS, time);

        if(ordersList != null && ordersList.size() > 0){
            ordersList.forEach(order -> {
                order.setStatus(Orders.COMPLETED);
                orderMapper.update(order);
            });
        }
    }
}
